﻿using Furion;
using GMS.NET.Core;
using GMS.NET.Core.Options;
using GMS.NET.Core.Provider.Logger;
using GMS.NET.Core.Tools;
using GMS.NET.Core.Users;
using GMS.NET.Web.Core.IFilters;
using GMS.NET.Web.Core.Security;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Text.Encodings.Web;
using System.Text.Unicode;

namespace GMS.NET.Web.Core
{
    public sealed class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConfigurableOptions<FrontendOptions>();
            services.AddConfigurableOptions<UserAdminOptions>();
            services.AddConfigurableOptions<CustConnectionOptions>();
            services.AddConfigurableOptions<ApplicationOptions>();
            services.AddCorsAccessor();
            services.AddConsoleFormatter();
            services.AddJwt<JWTSafeHandler>();
            services.AddControllers().AddInjectWithUnifyResult<IApiResultProvider>().AddJsonOptions(x =>
            {
                //防止序列化中文被Unicode编码
                x.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });
            services.AddRazorPages();
            //Api拦截器 全局作用
            services.AddMvcFilter<ApiFilter>();
            services.AddEventBus(builder =>
            {
                // 订阅 EventBus 意外未捕获异常
                builder.UnobservedTaskExceptionHandler = async (obj, args) =>
                {
                    await FileTool.WriteText($"/EventError/{DateTime.Now.ToString("yyyyMMdd")}.txt", args.Exception.Message);
                };
            });
            //微软ILogger扩展
            services.AddSingleton<ILoggerProvider>(new LoggerProvider($"Logger/{DateTime.Now:yyyyMMdd}.txt"));
            services.AddLogging();
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            // 添加规范化结果状态码，需要在这里注册
            app.UseUnifyResultStatusCodes();

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject();

            app.UseEndpoints(endpoints =>
            {
                // 注册集线器
                endpoints.MapHubs();

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapRazorPages();

            });

        }
    }
}